package com.sita.cfmoto.interact.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;

import com.malinskiy.superrecyclerview.OnMoreListener;
import com.malinskiy.superrecyclerview.SuperRecyclerView;
import com.sita.cfmoto.R;
import com.sita.cfmoto.event.ReleaseDynamicEvent;
import com.sita.cfmoto.interact.adapter.TopicDetailAdapter;
import com.sita.cfmoto.rest.model.Dynamic;
import com.sita.cfmoto.rest.model.Topic;
import com.sita.cfmoto.utils.InteractUtils;
import com.sita.cfmoto.utils.LocalStorage;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

public class TopicDetailActivity extends AppCompatActivity {
    private final long REFRESH_START = 1420070400000l;
    @Bind(R.id.topic_rv)
    SuperRecyclerView topicDetailListView;
    private Topic topic;
    private LinearLayoutManager linearLayoutManager;
    private TopicDetailAdapter topicDetailAdapter;
    private int size = 10;
    private int currentPage = 0;
    private Long minId = 0L;
    private String topicId;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dynamic_list_of_topic);
        ButterKnife.bind(this);
        topic = (Topic) getIntent().getSerializableExtra("topic");
        topicId = topic.topicId;
        LocalStorage.setTopicDynamicListRefreshTime(REFRESH_START);
        initTopicDetail();
        EventBus.getDefault().register(this);
    }


    @OnClick(R.id.join_topic_btn)
    void onClickJoin() {
        Intent intent = new Intent();
        intent.setClass(this, ReleaseDynamicActivity.class);
        intent.putExtra("topicId", topicId);
        startActivity(intent);
    }

    @OnClick({R.id.cancel})
    void onClickBack() {
        this.finish();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEventMainThread(ReleaseDynamicEvent event) {
        if (event.type == 1) {
            currentPage = 0;
            requestData();
        }
    }

    private void initTopicDetail() {
        linearLayoutManager = new LinearLayoutManager(this);
        topicDetailListView.setLayoutManager(linearLayoutManager);
        topicDetailAdapter = new TopicDetailAdapter();
        topicDetailListView.setAdapter(topicDetailAdapter);
        //设置分割线
        HorizontalDividerItemDecoration dividerItemDecoration = new HorizontalDividerItemDecoration.Builder(this)
                .color(getResources().getColor(R.color.common_background))
                .size(20)
                .showLastDivider()
                .build();
        topicDetailListView.addItemDecoration(dividerItemDecoration);
        //先把动态传进去，配置动态详情
        topicDetailAdapter.setTopicDetailItem(topic);
        //再根据话题id请求动态
        requestData();
        topicDetailListView.setupMoreListener(new OnMoreListener() {
            @Override
            public void onMoreAsked(int overallItemsCount, int itemsBeforeMore, int maxLastVisiblePosition) {
                currentPage++;
                requestData();
            }
        }, 1);
        topicDetailListView.setRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestData();
            }
        });
        topicDetailAdapter.setOnItemClickListener(new TopicDetailAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position, Dynamic dynamic) {
                Intent intent = new Intent();
                intent.setClass(TopicDetailActivity.this, DynamicDetailActivity.class);
                intent.putExtra("dynamic", dynamic);
                startActivity(intent);
            }
        });
    }

    private void requestData() {
        if (currentPage == 0) {
            //刷新参与本话题的动态列表
            long beginTime = LocalStorage.getTopicDynamicListRefreshTime();
            long endTime = System.currentTimeMillis();
            InteractUtils.fetchDynamicList(1, size, currentPage, topicId, beginTime, endTime, null, minId, null, 2,new InteractUtils.FetchDynamicListCallback() {
                @Override
                public void onDynamicListFetched(List<Dynamic> dynamicList) {
                    if (dynamicList != null && !dynamicList.isEmpty()) {
                        minId = Long.parseLong(dynamicList.get(0).msgId);
                        topicDetailAdapter.setDynamicData(dynamicList);
                    } else {
                        topicDetailListView.setRefreshing(false);
                    }
                }
            });
            //更新话题详情，主要刷新参与人数
         InteractUtils.fetchTopic(topicId, new InteractUtils.FetchTopicCallback() {
             @Override
             public void onTopicFetched(Topic topic) {
                 if (topic!=null){
                     topicDetailAdapter.setTopicDetailItem(topic);
                 }
             }
         });
        } else {
            //更多
            final long endTime = LocalStorage.getDynamicListRefreshTime();
            final long maxId = minId;
            InteractUtils.fetchDynamicList(2, size, currentPage, topicId, null, endTime, maxId, null, null, 2,new InteractUtils.FetchDynamicListCallback() {
                @Override
                public void onDynamicListFetched(List<Dynamic> dynamicList) {
                    if (dynamicList != null && !dynamicList.isEmpty()) {
                        topicDetailAdapter.appendTopicData(dynamicList);
                    } else {
                        currentPage--;
                    }
                }
            });
        }
    }

}
